﻿using Jil;
using Newtonsoft.Json;
using System.Text;
namespace Athena.Codec.Implementations
{
    using Message;

    /// <summary>
    /// Json格式编码器
    /// 默认使用Jil
    /// 支持Newtonsoft.Json
    /// </summary>
    public class JsonRpcMessageEncoder : IRpcMessageEncoder
    {
        private Jil.Options _jilOptions = new Jil.Options(includeInherited: true);

        /// <summary>
        /// 消息编码返回byte[]
        /// </summary>
        /// <param name="rpcTransportMessage"></param>
        /// <returns></returns>
        public byte[] MessageEncoding(RpcTransportMessage rpcTransportMessage)
        {
            var messageJsonString = JilJsonEncoding(rpcTransportMessage);
            return Encoding.UTF8.GetBytes(messageJsonString);
        }

        /// <summary>
        /// 消息解码返回String
        /// </summary>
        /// <param name="rpcTransportMessage"></param>
        /// <returns></returns>
        public string MessageEncodingString(RpcTransportMessage rpcTransportMessage)
        {
            return JilJsonEncoding(rpcTransportMessage);
        }

        /// <summary>
        /// Newtonsoft解码返回string
        /// </summary>
        /// <param name="rpcTransportMessage"></param>
        /// <returns></returns>

        public string NewtonsoftJsonEncoding(RpcTransportMessage rpcTransportMessage)
        {
            return JsonConvert.SerializeObject(rpcTransportMessage);
        }

        /// <summary>
        /// Jil解码返回string
        /// </summary>
        /// <param name="rpcTransportMessage"></param>
        /// <returns></returns>
        public string JilJsonEncoding(RpcTransportMessage rpcTransportMessage)
        {
            return JSON.SerializeDynamic(rpcTransportMessage, _jilOptions);
        }
    }
}
